package cn.lijigou.shopping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.ShoppingsActivity.MadapterShop.ViewHolderShop;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.LoadImageAysnc;
import cn.lijigou.shopping.util.LoadImageAysnc.ImageCallBack;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;


/**
 * @author 黄明
 * @version 创建时间：2012-4-6 上午11:30:49 
 * 类说明  关注 今日团购list页面
 */
public class TodayBuyActivity extends Activity implements OnClickListener,OnItemClickListener {
	private ListView buysite_list;
	public static  List<List<Shop>> dataSource = new ArrayList<List<Shop>>();
	public static boolean[] isload = {true,true,true,true};
	public static int[] dataPage = {1,1,1,1};
	public static int dataType=1;
	public static String cat="1";
	public static int order=2;
	private String id;
	private View footerView;
	private View load_one;
	private View load_two;
	private int page=1;
	private String selectCity="";
	private MainTabActivity parentView;
	private TextView title_btn_left;
	private Boolean isBuySite=false;
	private Timer timer= null;
	private TextView today_btn3;
	private TextView today_btn1;
	private Listadapter adapter;
	private String [] conten;
	public static  List<String> recordError=new ArrayList<String>();
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler waitHander = new Handler(){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			if(msg.what==1){
				adapter.setDate(new ArrayList(dataSource.get(dataType)));
				adapter.notifyDataSetChanged();
			}else if(msg.what==3){
				title_btn_left.setText(MSystem.selectCity);
			}else if(msg.what==101){
				load_one.setVisibility(View.VISIBLE);
				load_two.setVisibility(View.GONE);
			}else if(msg.what==102){
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
			}else if(msg.what==103){
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.VISIBLE);
			}else if(msg.what==104){
				
				if(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()==0){
					 Toast.makeText(TodayBuyActivity.this,"亲,没有分类数据哦,请查看别的分类", 1).show(); 
				}else{
					 Toast.makeText(TodayBuyActivity.this,"亲,已经是最后一条了哦", 1).show(); 
				}
				load_one.setVisibility(View.GONE);
				load_two.setVisibility(View.GONE);
			}
		}
	};
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE); 
		setContentView(R.layout.shoppings);
		initViews();
		if(this.getIntent().hasExtra("id")){
			id=this.getIntent().getStringExtra("id");
			isBuySite=true;
		}
		getShops();
		
	}
	private void initViews() {
		// TODO Auto-generated method stub
		for(int i=0;i<4;i++){
			dataSource.add(new ArrayList<Shop>());
		}
		parentView=(MainTabActivity)TodayBuyActivity.this.getParent();
		today_btn1 = (TextView)findViewById(R.id.Home_btn1);
		TextView today_btn2 = (TextView)findViewById(R.id.Home_btn2);
		today_btn3 = (TextView) this.findViewById(R.id.Home_btn3);
		
		
		
	    ((RelativeLayout)findViewById(R.id.home_left)).setOnClickListener(this);
	    ((RelativeLayout)findViewById(R.id.home_center)).setOnClickListener(this);
	    ((RelativeLayout)findViewById(R.id.home_right)).setOnClickListener(this);
	    conten=TodayBuyActivity.this.getResources().getStringArray(R.array.select_sort);
		
		
//		today_btn1.setOnClickListener(this);
//		today_btn2.setOnClickListener(this);
//		today_btn3.setOnClickListener(this);
		
		
		
		
		today_btn1.setText("分类");
		today_btn2.setText("人气");
		today_btn3.setText("价格");
		buysite_list = (ListView)this.findViewById(R.id.lv_shops);
		adapter = new Listadapter(this, new ArrayList(), buysite_list);
		
		this.findViewById(R.id.title_left_icon).setVisibility(View.VISIBLE);
		footerView= LayoutInflater.from(this).inflate(R.layout.list_bottom_line, null);
		load_one=footerView.findViewById(R.id.load_one);
		load_two=footerView.findViewById(R.id.load_two);
		
		if(!HomeActivity.isload[HomeActivity.dataType]){
			load_one.setVisibility(View.GONE);
		}else{
			load_one.setVisibility(View.VISIBLE);
		}
		load_two.setVisibility(View.GONE);
		load_two.setOnClickListener(this);
		buysite_list.addFooterView(footerView);
		buysite_list.setAdapter(adapter);
		buysite_list.setOnItemClickListener(this);
		buysite_list.setOnScrollListener(listScrollListenerShop);
		findViewById(R.id.titleRightView).setVisibility(View.GONE);
		title_btn_left=(TextView)this.findViewById(R.id.title_btn_left);
		title_btn_left.setOnClickListener(this);
		title_btn_left.setText("城市");
		findViewById(R.id.titleLeftView).setOnClickListener(this);
		
		
		this.findViewById(R.id.title_btn_right).setVisibility(View.GONE);
		((TextView)this.findViewById(R.id.text_center)).setText("今日团购");
	}
	
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(MSystem.selectCity.equals("")){
			title_btn_left.setText("城市");
		}else{
			title_btn_left.setText(MSystem.selectCity);
		}
		if(!(selectCity.trim().equals(MSystem.selectCity.trim())))
		{
			today_btn1.setText("分类");
			today_btn3.setText("价格");
			dataType=1;
			order=2;
			dataPage[dataType]=1;
			cat="1";
			MSystem.area="";
			MSystem.areaName="";	
			selectCity=MSystem.selectCity.trim();
			initDataSource();
			adapter.setDate(new ArrayList());
			adapter.notifyDataSetChanged();
			getShops();
			
			
			
			
		}
		
		if(!TodayBuyActivity.isload[TodayBuyActivity.dataType]){
			load_one.setVisibility(View.GONE);
		}else{
			load_one.setVisibility(View.VISIBLE);
		}
		
	}
	
	private void initDataSource() {
		// TODO Auto-generated method stub
		for(int i=0;i<dataSource.size();i++){
			dataSource.get(i).clear();
			dataPage[i]=1;
			isload[i]=true;
		}
	}
	
	private void setCity() {
		  TimerTask task = new TimerTask() { 
				public void run() { 
					if(MSystem.mLocation!=null){
						waitHander.sendEmptyMessage(3);
						timer.cancel();
					}
					 if(!"".equals(MSystem.selectCity)){//如果用户选择了城市  就不在自动显示城市
						 timer.cancel();
					 }
				} 
			}; 
		 timer = new Timer(); 
		 timer.schedule(task,0,1500);
}
	public class Listadapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private List<Shop>  shopList;
		private Boolean refresh=true;
		private ListView listView;
		private LoadImageAysnc loadImageAysnc;
		public  class ViewHolderShop {
			public ImageView shop_image;
			private TextView info;
			private TextView current_price;
			private TextView distance;
			private TextView saved_price;
			public Integer shopid;
			private TextView source;
			private TextView address;
			private String imageUrl;
			private Drawable shop_drawable;
		}
		public Listadapter(Activity a,List<Shop> shopList,ListView listview) {
			this.mInflater = LayoutInflater.from(a);
			this.shopList=shopList;
			this.listView = listview;
			loadImageAysnc = new LoadImageAysnc(a);
		}

		public Listadapter() {
			// TODO Auto-generated constructor stub
		}

		public int getCount() {
//			return shopList.size();
			return shopList.size();
		}

		public void setDate(List<Shop> shopList) {
			
			refresh=true;
			this.shopList=shopList;
		}
		
		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}
		ViewHolderShop holder = null;
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				holder = new ViewHolderShop();
				convertView = mInflater.inflate(R.layout.list_item_shop, null);
				holder.shop_image = (ImageView) convertView.findViewById(R.id.shop_image);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				holder.current_price = (TextView) convertView.findViewById(R.id.current_price);
				holder.distance = (TextView) convertView.findViewById(R.id.distance);
				holder.saved_price = (TextView) convertView.findViewById(R.id.saved_price);
				holder.source = (TextView) convertView.findViewById(R.id.source);
				holder.address = (TextView) convertView.findViewById(R.id.address);
				
				convertView.setTag(holder);
			} else {
				holder = (ViewHolderShop) convertView.getTag();
			}
			TextPaint tp = holder.saved_price.getPaint();
            tp.setFakeBoldText(true); 

			Shop shop = shopList.get(position);
			String  current_price = shop.getPrice();
			String  source = shop.getSource();   
			String  info = shop.getTitle();
			String  distance = shop.getDistance();
			String 	old_price = shop.getValue();
			String  flower_title = shop.getTitle();
			holder.address.setText(shop.getShop_address());
			holder.source.setText(shop.getSource());
			
			final String imageUrl = shop.getPhoto_small();
    		final String id = shop.getId();
    		int shopid=0;
    		try{
    			 shopid=Integer.parseInt(id);
    		}catch (Exception e) {
				// TODO: handle exception
    			shopid=0;
    			e.printStackTrace();
			}
//    		holder.progressBar.setTag(imageUrl);
			holder.shop_image.setTag(id);
			
			
			
			
			//开始异步加载数据
			Drawable drawable = loadImageAysnc.loadImage(position,shopList.get(position).getId(), shopList.get(position).getPhoto_small(), "small.jpg",new ImageCallBack() {
				
				
				public void imageLoaded(Drawable drawable, int iconSrc) {
					// TODO Auto-generated method stub
					ImageView imageViewTag = (ImageView) listView.findViewWithTag(id);
					if(imageViewTag != null) {
						imageViewTag.setBackgroundDrawable(drawable);
					}
					ProgressBar progressBar = (ProgressBar) listView.findViewWithTag(imageUrl);
					if(progressBar != null) {
						progressBar.setVisibility(View.GONE);
					}
					
				}
			} );
				
			
			if(drawable == null) {
				 holder.shop_image.setBackgroundResource(R.drawable.load_small);
			} else {
				 holder.shop_image.setBackgroundDrawable(drawable);
			}
			
			source = source.replaceAll(" ", "");
			holder.info.setText(info);
			holder.distance.setVisibility(View.VISIBLE);
			try{  
				if(isNull(distance)){
					Double mDistance = Double.parseDouble(distance);
					if(mDistance == 0.0){
						holder.distance.setVisibility(View.GONE);
					}else if( mDistance >0 & mDistance <1000 ){
						holder.distance.setText(mDistance+"m");
						
					}else if(mDistance>1000){
						mDistance = mDistance/1000;
						BigDecimal b = new BigDecimal(mDistance);  
						double f1 = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();  
						holder.distance.setText(f1+"km");
					}
				}
				
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			if(isNull(current_price)&&!current_price.equals(getIdToString(R.string.No_).trim())){
					if((HomeActivity.dataType+"").equals("76") | (HomeActivity.dataType+"").equals("77") | (HomeActivity.dataType+"").equals("78")){
						holder.current_price.setTextColor(Color.BLACK);
						holder.current_price.setTextSize(13);
						holder.current_price.setText(getIdToString(R.string.discount_limit));
					}else{
						holder.current_price.setText(getIdToString(R.string.current_price_symbol)+current_price);
					}
				}else{
					holder.current_price.setText(getIdToString(R.string.price_No));
				}
			if(isNull(old_price)&&!old_price.equals(getIdToString(R.string.No_).trim())){
				Double mSavePrice = Double.parseDouble(old_price)-Double.parseDouble(current_price);
				BigDecimal b = new BigDecimal(mSavePrice);  
				double f1 = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue(); 
				
				if((HomeActivity.dataType+"").equals("76") | (HomeActivity.dataType+"").equals("77") | (HomeActivity.dataType+"").equals("78")){
					holder.saved_price.setTextColor(Color.RED);
					holder.saved_price.setTextSize(14);
					holder.saved_price.setText(getIdToString(R.string.current_price_symbol)+new BigDecimal(Double.parseDouble(current_price)).setScale(1,java.math.BigDecimal.ROUND_HALF_UP));
				}else{
					holder.saved_price.setText(getIdToString(R.string.save)+ f1);
				}
				
				
//				holder.old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
			}else{
				holder.saved_price.setText(getIdToString(R.string.no_original_price));
			}
			convertView.invalidate();
			return convertView;
		}
	}
	
	private OnScrollListener listScrollListenerShop = new ListView.OnScrollListener(){
        public void onScroll(AbsListView arg0,
                        int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        	   if (totalItemCount <= 0){
                    return;
                }
                if (firstVisibleItem + visibleItemCount >= (totalItemCount)&&totalItemCount!=1){
                	getShops();
                }
        }
		
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			
		}
	};
	
	
	public void onClick(View v) {
		MSystem.pv+=1;
		// TODO Auto-generated method stub
		switch (v.getId()) {
		
		case R.id.titleLeftView:
			Intent intents = new Intent(TodayBuyActivity.this, ChangeCityActivity.class);
			intents.putExtra("from", "today");
			TodayBuyActivity.this.startActivityForResult(intents,1);
			break;

		
		case R.id.home_left:
			
			choose_sort();
			break;
		case R.id.home_center:
			dataType=1;
			order=2;
			today_btn1.setText("分类");
			today_btn3.setText("价格");
			
			if(dataSource.get(dataType).size()==0){
				dataPage[dataType]=1;
				cat="1";
				
				isload[dataType]=true;
				adapter.setDate(new ArrayList());
				adapter.notifyDataSetChanged();
				getShops();
			}else{
				adapter.setDate(dataSource.get(dataType));
				adapter.notifyDataSetChanged();
			}
			break;
		case R.id.home_right:
			/**
			 * 获得今日团购
			 * @param shops
			 * @param page
			 * @param sort 	1 为默认人气    2  为分类(1美食天下,2休闲娱乐,3网购精品,4生活服务，7酒店旅游，默认为1) 3 为价格
			 * @param order 排序方法：1正序，2倒序
			 * @param cat 	sort=2 的分类
			 * @return
			 */		
				today_btn1.setText("分类");
				dataType=3;
				if(order==2){
					order=1;
					today_btn3.setText("由低到高");
					
				}else{
					order=2;
					today_btn3.setText("由高到低");
				}
				dataSource.get(dataType).clear();
				dataPage[dataType]=1;
				cat="1";
				isload[dataType]=true;
				adapter.setDate(new ArrayList());
				adapter.notifyDataSetChanged();
				getShops();	
		
			
			break;

		default:
			break;
		}
	}
	public Boolean isNull(String str){
		if(str!=null&&!str.equals("")&&str!=""&&!str.equals("null")){
			return true;
		}
		return false;
	}
	String getIdToString(int id){
		String string=this.getResources().getString(id);
		return string;
	}
	
	private void getShops(){
		if(recordError.contains(dataType+"")){
			recordError.remove(dataType+"");
			isload[dataType]=true;
		} 
		if(isload[dataType]){
			isload[dataType] = false;
    		//显示加载中
    		waitHander.sendEmptyMessage(101);
			if (getNetConnectState(TodayBuyActivity.this)) {
				if (MSystem.mLocation != null) {
					executorService.execute(new Thread() {
						public void run() {
							Boolean temp = false;
							if (dataSource.size() == 0) {
								page = 1;
							} else {
								page = page + 1;
							}
							MResult mResult;
							/**
							 * 获得今日团购
							 * 
							 * @param shops
							 * @param page
							 * @param sort
							 *            1 为默认人气 2
							 *            为分类(1美食天下,2休闲娱乐,3网购精品,4生活服务，7
							 *            酒店旅游，默认为1) 3 为价格
							 * @param order
							 *            排序方法：1正序，2倒序
							 * @param cat
							 *            sort=2 的分类
							 * @return
							 */
							if (dataSource.get(dataType).size() == 0) {
								dataPage[dataType] = 1;
							} else {
								dataPage[dataType] = dataPage[dataType] + 1;
							}
							// if(isBuySite){
							// mResult=MSystem.getShopsFromHotWebsite(dataSource.get(dataType),
							// cat,id, dataPage[dataType], dataType, order);
							// }else{
							mResult = MSystem.getShopsFromToday(dataSource.get(dataType), cat, dataPage[dataType], dataType, order);
							// }

							if (mResult != null) {
								if (mResult.isSuccess()) {
									waitHander.sendEmptyMessage(1);
									temp = mResult.isPage();
									if (!mResult.isPage()) {
										waitHander.sendEmptyMessage(102);
										if (dataSource.size() > 8) {
											MainTabActivity.showHander.sendEmptyMessage(102);
										}
									}
									if (dataType == 3) {
									}
								} else {
									waitHander.sendEmptyMessage(104);
								}
							} else {
								HomeActivity.dataPage[HomeActivity.dataType] = HomeActivity.dataPage[HomeActivity.dataType] - 1;
								recordError.add(dataType + "");
								waitHander.sendEmptyMessage(103);
							}
							isload[dataType] = temp;
						}
					});
				} else {
					recordError.add(dataType + "");
					waitHander.sendEmptyMessage(103);
				}
			}else{
					recordError.add(dataType+"");
					waitHander.sendEmptyMessage(103);
			}	
    	} 
	}
	
	public void choose_sort(){
		Dialog dialog = null;
		Builder b2 = new AlertDialog.Builder(this);
		b2.setTitle("分类");
        b2.setItems(R.array.select_sort, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	today_btn1.setText(conten[which]);
            	today_btn3.setText("价格");
            	dataType=2;
            	order=2;
            	if(which == 0){
            		cat="1";
            	}else if(which == 1){
            		cat="2";
            	}else if(which == 2){
            		cat="4";
            	}else if(which == 3){
            		cat="7";
            	}
            	dataSource.get(dataType).clear();
            	isload[dataType]=true;
            	dataPage[dataType]=1;
            	adapter.setDate(new ArrayList());
				adapter.notifyDataSetChanged();
				getShops();
            	
            }});
        dialog = b2.create();
        dialog.show();
	}
	
	public boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
//    		MSystem.exit(this);
    		if(parentView != null){
    			Animation animation=AnimationUtils.loadAnimation(TodayBuyActivity.this,R.anim.home_push_rightout);
    			parentView.mHost.getCurrentView().startAnimation(animation);
        		parentView.mHost.setCurrentTab(0);	
    			parentView.main_tab_home.setChecked(true);
			    Animation animations=AnimationUtils.loadAnimation(TodayBuyActivity.this,R.anim.home_push_rightin);
			    parentView.mHost.getCurrentView().startAnimation(animations);
    		}else{
    			this.finish();
    			
    		}

		
    		return true;
	    }else{
	    	return super.onKeyDown(keyCode, event);
	    }
    }
	
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		MSystem.detail+=1;
		MSystem.pv+=1;
		if(TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()!=0&&position<TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).size()){
			Shop shop = TodayBuyActivity.dataSource.get(TodayBuyActivity.dataType).get(position);
			Intent intent_shop = new Intent(TodayBuyActivity.this, TodayDetailActivity.class);
			intent_shop.putExtra("position", position);
//			intent_shop.putExtra("all_flower_data", all_flower_data);
//			if((HomeActivity.dataType+"").equals("76") | (HomeActivity.dataType+"").equals("77") | (HomeActivity.dataType+"").equals("78")){
//				intent_shop.putExtra("flower",true);
//			}
			TodayBuyActivity.this.startActivity(intent_shop);
		}
		
		
	}
}

